package com.qzsoft.zhjd.machine.modules.machineinfo.service.impl;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qzsoft.zhjd.machine.modules.machineinfo.mapper.MachineInfoMapper;
import com.qzsoft.jeemis.common.utils.ConvertDictUtils;
import com.qzsoft.zhjd.common.components.BaseServiceComponent;
import com.qzsoft.zhjd.common.enums.BizCode;
import com.qzsoft.zhjd.common.utils.RenExceptionUtils;
import com.qzsoft.zhjd.machine.modules.machineinfo.dto.MachineInfoBookListDto;
import com.qzsoft.zhjd.machine.modules.machineinfo.entity.MachineInfoEntity;
import com.qzsoft.zhjd.machine.modules.machineinfo.service.MachineInfoDriverService;
import com.qzsoft.zhjd.machine.modules.machineinfo.service.MachineInfoService;

/**
 * @ClassName MachineInfoServiceImpl
 * @Description 机械设备业务接口实现
 * @author linhuawei
 * @since 2021-11-01
 */
@Service
public class MachineInfoServiceImpl extends ServiceImpl<MachineInfoMapper, MachineInfoEntity>
        implements MachineInfoService {

    @Autowired
    private MachineInfoDriverService machineInfoDriverService;

    @Autowired
    private BaseServiceComponent baseServiceComponent;

    @Override
    public IPage<MachineInfoEntity> page(Map<String, Object> params) {
        // 判断参数是否存在
        if (null == params) {
            params = new HashMap<String, Object>();
        }

        // 执行查询操作
        IPage<MachineInfoEntity> page = baseServiceComponent.getPage(params, MachineInfoEntity.class);
        QueryWrapper<MachineInfoEntity> queryWrapper = baseServiceComponent.getQueryWrapper(params,
                MachineInfoEntity.class, "name");
        queryWrapper.orderByDesc("create_date");
        page = baseMapper.selectPage(page, queryWrapper);
        return ConvertDictUtils.formatDicDataPage(page);
    }

    @Override
    public IPage<MachineInfoBookListDto> bookPage(Map<String, Object> params) {
     // 判断参数是否存在
        if (null == params) {
            params = new HashMap<String, Object>();
        }

        // 执行查询操作
        IPage<MachineInfoBookListDto> page = baseServiceComponent.getPage(params, MachineInfoBookListDto.class);
        page = baseMapper.bookPage(page, params);
        return ConvertDictUtils.formatDicDataPage(page);
    }

    @Override
    public List<MachineInfoEntity> list(Map<String, Object> params) {
        // 判断参数是否存在
        QueryWrapper<MachineInfoEntity> queryWrapper = null;
        if (null != params) {
            queryWrapper = baseServiceComponent.getQueryWrapper(params, MachineInfoEntity.class, "name");
        }

        List<MachineInfoEntity> list = baseMapper.selectList(queryWrapper);
        return ConvertDictUtils.formatDicDataList(list);
    }

    @Override
    public MachineInfoEntity getByMachineKey(String machineKey) {
        QueryWrapper<MachineInfoEntity> queryWrapper = new QueryWrapper<MachineInfoEntity>();
        queryWrapper.eq("machine_key", machineKey);
        List<MachineInfoEntity> list = baseMapper.selectList(queryWrapper);
        if (ObjectUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(MachineInfoEntity entity) {
        // TODO 添加第三方平台信息
        
        // 判断资产编号是否重复
        QueryWrapper<MachineInfoEntity> queryWrapper = new QueryWrapper<MachineInfoEntity>();
        queryWrapper.eq("asset_number", entity.getAssetNumber());
        Integer count = baseMapper.selectCount(queryWrapper);
        if(null != count && 0 < count) {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "资产编号[" + entity.getAssetNumber() + "]已经存在");
        }
        

        // 执行添加操作
        entity.setDeprMonthValue(countDeprMonthValue(entity));
        return super.save(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(MachineInfoEntity entity) {
        // TODO 修改第三方平台信息

        // 执行修改操作
        entity.setDeprMonthValue(countDeprMonthValue(entity));
        return super.updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Serializable id) {
        // TODO 删除第三方平台信息

        // 删除机械设备驾驶员信息
        machineInfoDriverService.deleteByMachineId(id);

        // 删除机械设备
        return super.removeById(id);
    }

    /**
     * @Title countDeprMonthValue
     * @Description 计算每月折旧金额
     */
    private BigDecimal countDeprMonthValue(MachineInfoEntity entity) {
        // 判断必要数据是否为空
        BigDecimal originalValue = entity.getOriginalValue();
        Integer deprMaxMonth = entity.getDeprMaxMonth();
        Date deprStartDate = entity.getDeprStartDate();
        if (null == originalValue) {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "资产原值不可为空");
        }
        if (null == deprMaxMonth) {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "最大折旧月份不可为空");
        }
        if (null == deprStartDate) {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "开始折旧日期不可为空");
        }
        // 如果最大折旧月份小于0，不做处理
        if(0 <= deprMaxMonth) {
            return BigDecimal.ZERO;
        }
        
        // 计算每月折旧金额
        BigDecimal value = originalValue.multiply(new BigDecimal(0.95));
        return value.divide(new BigDecimal(deprMaxMonth), RoundingMode.HALF_UP);
    }

    @Override
    public MachineInfoEntity getById(Serializable id) {
    	MachineInfoEntity entity = baseMapper.selectById(id);
    	if(null != entity) {
    		entity = ConvertDictUtils.formatDicData(entity);
    	}
    	return entity;
    }
    
}
